import { defineStore } from 'pinia';
import { store } from '@/store';
import { storage } from '@/utils/Storage';
import { websiteConfig } from '@/config/website.config';
import * as constants from '@/config/constants';
import { format } from 'date-fns';
import PenWorker from '@/components/Pen/pen.worker?worker';
import {getBookPageInfoByKey, getIntegralSetting} from '@/api/course';

export interface StudentInfo {
  id?: number;
  age: number;
  birthday: string;
  contactPersonName: string;
  contactPersonPhone: string;
  gender: number;
  learningStageId: number;
  learningStageName: string;
  name: string;
  number: string;
  pic: string;
  teacherId: number;
  teacherName: string;
}
export interface CoursePenDataType {
  mac: string;
  status: number;
  studentInfo?: StudentInfo | null;
  waitWriteData?: any;
}
export interface GoodDialogDataType {
  title?: string;
  content?: string;
}
export interface IconSettingList {
  icon: string;
  max: number;
  min: number;
  scope: number;
}
export interface IntegralSettingDataType{
  iconSettingList: IconSettingList[];
  rate: number;
}
// AP状态 在线 | 离线 | 未配置
export type ApStatus = 'on-line' | 'off-line' | 'off-config';
export interface CourseState {
  // 页面路由名称
  pageRoute: string;
  // 课程ID
  courseId: string;
  // 课程开始时间戳
  courseStartTime: number;
  // AP的IP
  apIp: string;
  // AP状态
  apStatus: ApStatus;
  // 主websocket
  websocket: any;
  // 课程的笔
  coursePenData: CoursePenDataType[];
  // 已扫描到的笔
  scannedPenData: any[];
  // 已绑定的笔
  bindPenData: any[];
  // 已连接的笔
  connectedPenData: any[];
  // 监听笔连接状态日志
  listenerPenStatusLogData: any[];
  // 轮询
  interval: any;
  // 离线测试名称
  offLineTestName: string;
  // 离线次数
  offLineTestNum: number;
  // 开始时间
  offLineTestStartTime: string;
  // 离线测试定时器
  offLineTestInterval: any;
  // 当前课程的学生集合
  studentData: StudentInfo[];
  // 当前课程的学生和Pen的绑定关系
  studentMapBindInfo: any;
  // 教材信息
  bookMapData: any[];
  requestBookDataTime: number;
  // 实时笔迹弹窗显示
  canvasDialogVisible: boolean;
  // 待嘉奖 学生数据
  goodDialogStudentData: any;
  // 待嘉奖 学生数据
  badDialogStudentData: any;
  // 积分配置
  integralSettingData: IntegralSettingDataType;
}

const getNowDate = () => format(Date.now(), 'yyyy-MM-dd hh:mm:ss');

export const useCourseStore = defineStore({
  id: 'app-course',
  state: (): CourseState => ({
    pageRoute: 'dashboard',
    courseId: storage.get('COURSE-ID', ''),
    courseStartTime: storage.get('COURSE-START-TIME', 0),
    apIp: '',
    apStatus: 'off-line',
    websocket: null,
    scannedPenData: [],
    bindPenData: [],
    connectedPenData: [],
    coursePenData: storage.get('COURSE-PEN-DATA', []),
    listenerPenStatusLogData: [],
    interval: null,
    offLineTestName: '',
    offLineTestNum: 0,
    offLineTestStartTime: '',
    offLineTestInterval: null,
    studentData: [],
    studentMapBindInfo: storage.get('student-Map-Bind-Info', null),
    bookMapData: storage.get('BOOK-MAP-DATA', []),
    requestBookDataTime: 0,
    canvasDialogVisible: false,
    goodDialogStudentData: [],
    badDialogStudentData: [],
    integralSettingData: storage.get('integral-Setting-Data', {
      iconSettingList: [],
      rate: 0
    }),
  }),
  getters: {
    getApStatus(): ApStatus {
      return this.apStatus;
    },
    getPageRoute(): string {
      return this.pageRoute;
    },
    getCurrentCourseData(): any {
      return {
        courseId: this.courseId,
        courseStartTime: this.courseStartTime
      };
    },
    getScannedPenData(): any[] {
      return this.scannedPenData;
    },
    getBindPenData(): any[] {
      return this.bindPenData;
    },
    getConnectedPenData(): any[] {
      return this.connectedPenData;
    },
    getCoursePenData(): CoursePenDataType[] {
      return this.coursePenData;
    },
    getBookMapData(): any {
      return this.bookMapData;
    },
    getStudentData(): any[] {
      return this.studentData;
    },
    getCanvasDialogVisible(): boolean {
      return this.canvasDialogVisible;
    },
    getGoodDialogStudentData(): any {
      return this.goodDialogStudentData;
    },
    getBadDialogStudentData(): any {
      return this.badDialogStudentData;
    },
    getIntegralSettingData(): IntegralSettingDataType {
      return this.integralSettingData;
    },
  },
  actions: {
    setApId(ip) {
      this.apIp = ip;
    },
    setApStatus(status: ApStatus) {
      this.apStatus = status;
    },
    setPageRoute(route: string) {
      this.pageRoute = route;
    },
    setCurrentCourseData(data) {
      this.courseId = data.courseId;
      this.courseStartTime = data.courseStartTime;
      storage.set('COURSE-ID', data.courseId);
      storage.set('COURSE-START-TIME', data.courseStartTime);
    },
    setStudentData(data) {
      this.studentData = data;
    },
    setCoursePenData(data) {
      this.coursePenData = data;
      storage.set('COURSE-PEN-DATA', data);
    },
    setBookData(data) {
      this.bookMapData = data;
      storage.set('BOOK-MAP-DATA', data);
    },
    setCanvasDialogVisible(data) {
      this.canvasDialogVisible = data;
    },
    setGoodDialogStudentData(data) {
      this.goodDialogStudentData = data;
    },
    setBadDialogStudentData(data) {
      this.badDialogStudentData = data;
    },
    setIntegralSettingData(data) {
      this.integralSettingData = data;
      storage.set('integral-Setting-Data', data)
    },
    calcIntegralSettingData (score) {
      score = parseInt(score)
      for (let i = 0; i < this.integralSettingData.iconSettingList.length; i++) {
        const v = this.integralSettingData.iconSettingList[i];
        if (v.min <= score && v.max >= score) {
          return v
        }
      }
    },
    connectWebsocket() {
      this.websocket = new WebSocket(`ws://${websiteConfig.apServerUrl}/ws/newap/new_ap_collect`);
      this.websocket.onopen = (e) => {
        console.log('onopen', e);
      };
      this.websocket.onclose = (e) => {
        console.log('onclose', e);
        this.stopPollScanPen();
      };
      this.websocket.onerror = (e) => {
        console.log('onerror', e);
        this.stopPollScanPen();
      };
      this.websocket.onmessage = (e) => {
        const data = JSON.parse(e.data);
        // console.log(this.scannedPenData)
        // console.log(this.bindPenData)
        // console.log(this.connectedPenData)
        switch (data.msgId) {
          case constants.WEBSOCKET_CONNECT_SUCCESS:
            this.pollScanPen();
            this.getBindPen();
            this.getConnectPen();
            break;
          case constants.PEN_CONNECTION_STATUS:
            // 0-断开 1-连接
            if (data.status === 0 && this.offLineTestNum !== 0) {
              // 断线情况存入数据库
              this.savePenOfflineLog(data.mac);
            }
            if (data.status === 1) {
              this.scannedPenData = this.scannedPenData.filter((i) => i.mac !== data.mac);
              if (this.connectedPenData.some((i) => i.mac === data.mac)) {
                return;
              }
              this.connectedPenData.push({
                mac: data.mac,
                checked: false,
              });
            }
            if (data.status === 0) {
              this.connectedPenData = this.connectedPenData.filter((i) => i.mac !== data.mac);
              if (this.scannedPenData.some((i) => i.mac === data.mac)) {
                return;
              }
              this.scannedPenData.push({
                mac: data.mac,
                checked: false,
              });
            }
            const findIndex = this.coursePenData.findIndex((i) => i.mac === data.mac);
            if (findIndex > -1) {
              this.coursePenData[findIndex].status = data.status;
            } else {
              const penItem = {
                mac: data.mac,
                status: data.status,
                studentInfo: null,
              };
              this.coursePenData.push(penItem);
            }

            // this.setCoursePenData(this.coursePenData);
            let otherData: any = [];
            for (let i = 1; i <= 40; i++) {
              otherData.push({
                mac: '001B100001BA_ap' + i,
                status: 1,
                studentInfo: {
                  id: 's' + i,
                  name: '学生' + i
                },
              })
            }

            this.setCoursePenData(otherData);
            const { mac, ap, status } = data;
            // 日志
            this.listenerPenStatusLogData.push({
              mac,
              ap,
              status: status ? '连接' : '断开',
              time: getNowDate(),
            });
            this.getBindPen();
            break;
          case constants.SCAN_PEN:
            if (this.bindPenData.length === 60) {
              this.stopPollScanPen();
              return;
            }
            if (data.mac === 'FFFFFFFFFFFF') {
              return;
            }
            if (this.scannedPenData.some((i) => i.mac === data.mac)) {
              return;
            }
            this.scannedPenData.push({
              mac: data.mac,
              checked: false,
            });
            this.bindPen(data.mac);
            break;
          case constants.BIND_PEN:
            break;
          case constants.UNBIND_PEN:
            //
            break;
          case constants.GET_BIND_PEN:
            // 获取已绑定的笔列表
            this.bindPenData = data.mac_list.map((mac) => {
              const findIndex = this.coursePenData.findIndex((i) => i.mac === mac);
              if (findIndex === -1) {
                const penItem = {
                  mac: mac,
                  status: 0,
                  studentInfo: null,
                };
                this.coursePenData.push(penItem);
              }
              return {
                mac: mac,
                checked: false,
              };
            });

            if (this.bindPenData.length === 60) {
              this.stopPollScanPen();
              return;
            }
            break;
          default:
            break;
        }
      };
    },
    // 获取已连接的笔
    getConnectPen() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.PEN_CONNECTION_STATUS,
        })
      );
    },
    stopPollScanPen() {
      clearInterval(this.interval);
    },
    pollScanPen() {
      this.interval = setInterval(() => {
        this.scanPen();
      }, 5000);
    },
    // 扫描周围笔
    scanPen() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.SCAN_PEN,
          ap: this.apIp,
        })
      );
    },
    // 获取已绑定的笔
    getBindPen() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.GET_BIND_PEN,
          ap: this.apIp,
        })
      );
    },
    // 绑定笔
    bindPen(mac) {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.BIND_PEN,
          ap: this.apIp,
          mac,
        })
      );
    },
    // 批量绑定笔
    bindMorePen(state) {
      this.scannedPenData.filter((i) => i.checked).map((i) => this.bindPen(i.mac));
    },
    // 解绑笔
    unbindPen(mac) {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.UNBIND_PEN,
          ap: this.apIp,
          mac,
        })
      );
    },
    // 批量解绑笔
    unbindMorePen(state) {
      this.bindPenData.filter((i) => i.checked).map((i) => this.unbindPen(i.mac));
      this.connectedPenData.filter((i) => i.checked).map((i) => this.unbindPen(i.mac));
    },
    // 获取AP离线数据量
    getApOffLineDataSize() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.AP_OFFLINE_DATA_SIZE,
        })
      );
    },
    // 开始AP离线数据
    startApOffLineData() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.AP_START_OFFLINE_DATA,
        })
      );
    },
    // 停止AP离线数据
    stopApOffLineData() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.AP_STOP_OFFLINE_DATA,
        })
      );
    },
    // 暂停AP离线数据
    pauseApOffLineData() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.AP_PAUSE_OFFLINE_DATA,
        })
      );
    },
    // 继续AP离线数据
    continueApOffLineData() {
      this.websocket.send(
        JSON.stringify({
          msgId: constants.AP_CONTINUE_OFFLINE_DATA,
        })
      );
    },
    // 开始离线测试
    startOffLineTest(name) {
      this.offLineTestName = name;
      this.offLineTestNum++;
      this.offLineTestStartTime = getNowDate();
      this.offLineTestInterval = setInterval(() => {
        this.offLineTestNum++;
        this.offLineTestStartTime = getNowDate();
      }, 1000 * 60 * 20);
    },
    // 停止离线测试
    stopOffLineTest() {
      this.offLineTestNum = 0;
      clearInterval(this.offLineTestInterval);
      this.offLineTestInterval = null;
    },
    /** 存储笔断线日志 */
    async savePenOfflineLog(mac) {},
    /** 存储测试日志 */
    async saveTestLog({ penNum, offlineNum }) {},
  },
});

// Need to be used outside the setup
export function useCourse() {
  return useCourseStore(store);
}
